package com.bootdo.shop.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.bootdo.shop.domain.ProductDO;
import com.bootdo.shop.service.ProductCategoryService;
import com.bootdo.shop.service.ProductService;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.domain.CommonImageDO;
import com.bootdo.common.domain.FileDO;
import com.bootdo.common.exception.BDException;
import com.bootdo.common.service.CommonImageService;
import com.bootdo.common.service.FileService;
import com.bootdo.common.utils.FileType;
import com.bootdo.common.utils.FileUtil;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;

/**
 * 商品表
 * 
 * @author yhg
 * @email 1992lcg@163.com
 * @date 2017-12-14 17:24:57
 */
 
@Controller
@RequestMapping("/shop/product")
public class ProductController {
	@Autowired
	private ProductService productService;
	@Autowired
	private BootdoConfig bootdoConfig;
	@Autowired
	private FileService sysFileService;
	@Autowired
	private CommonImageService commonImageService;
	

	@GetMapping()
	@RequiresPermissions("shop:product:product")
	String Product(){
	    return "shop/product/product";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("shop:product:product")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<ProductDO> productList = productService.list(query);
		int total = productService.count(query);
		PageUtils pageUtils = new PageUtils(productList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("shop:product:add")
	String add(){
	    return "shop/product/add";
	}

	@GetMapping("/edit/{productId}")
	@RequiresPermissions("shop:product:edit")
	String edit(@PathVariable("productId") Long productId,Model model){
		ProductDO product = productService.get(productId);
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("commonId", productId);
		map.put("type", "product");
		List<CommonImageDO> imglist = commonImageService.list(map);
		
		List<String> imgs =new ArrayList<String>();
		if(imglist.size()>0) {
			
			for (CommonImageDO commonImageDO : imglist) {
				
				imgs.add(commonImageDO.getImageUrl());
				
			}
			
		}
		String strimgs = StringUtils.join(imgs.toArray(), ",");  
		
		product.setProimgs(strimgs);
		
	
		
		
		model.addAttribute("product", product);
		model.addAttribute("imgs", imgs);
	    return "shop/product/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("shop:product:add")
	public R save( ProductDO product){
		if(productService.save(product)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("shop:product:edit")
	public R update( ProductDO product){
		productService.update(product);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("shop:product:remove")
	public R remove( Long productId){
		if(productService.remove(productId)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("shop:product:batchRemove")
	public R remove(@RequestParam("ids[]") Long[] productIds){
		productService.batchRemove(productIds);
		return R.ok();
	}
	  /**
     */
	@PostMapping("/upload")
    @ResponseBody
    public Object upload(@RequestPart("file") MultipartFile file) {
      
		String fileName = file.getOriginalFilename();
		fileName = FileUtil.renameToUUID(fileName);
		FileDO sysFile = new FileDO(FileType.fileType(fileName), "/files/" + fileName, new Date());
		try {
			FileUtil.uploadFile(file.getBytes(), bootdoConfig.getUploadPath(), fileName);
		} catch (Exception e) {
			return R.error();
		}

		if (sysFileService.save(sysFile) > 0) {
			return R.ok().put("fileName",sysFile.getUrl());
		}
		return R.error();
    }
    
    @RequestMapping(method = RequestMethod.POST, path = "/uploadMore")
    @ResponseBody
    public Object uploadMore(String id,@RequestParam("file") MultipartFile[] files, HttpServletRequest request) {
    	
        String pictureName = UUID.randomUUID().toString() + ".jpg";
        String path = "";
        List<String> fileUrlList = new ArrayList<String>(); //用来保存文件路径，用于jsp页面回显用
        // 先判断文件files不为空
        if (files != null && files.length > 0) {
        	 for (MultipartFile file : files) { //循环遍历，取出单个文件，下面的操作和单个文件就一样了
        		 
        		 if (!file.isEmpty()) {//这个判断必须加上
        			 
        			// 获得原始文件名
                     String fileName = file.getOriginalFilename();
                     String newfileName = new Date().getTime() + String.valueOf(fileName);
                   //获得物理路径webapp所在路径
                     //String pathRoot = request.getSession().getServletContext().getRealPath("");
                  // 项目下相对路径
                     path = newfileName;
                     String fileSavePath = "D:/temp/upload/product/";
                  // 创建文件实例
                     File tempFile = new File(fileSavePath + path); //文件保存路径为pathRoot + path
                    
                     try {
                         // Transfer the received file to the given destination file. 
                         file.transferTo(tempFile);
                     } catch (IllegalStateException e) {
                         e.printStackTrace();
                     } catch (IOException e) {
                         e.printStackTrace();
                     }
                     fileUrlList.add(path);
        		 }
        		 
        	 }
        }
        Map<String,Object> map =new HashMap<String,Object>();
        map.put("id", id);
        map.put("filePath", path);
        //request.setAttribute("filePath ", fileUrlList); //保存路径，用于jsp页面回显
        return map;
    }
}
